<?php

/**
 * 微信企业支付公共类
 * @author smh <hi_shu@126.com> Created on 2015-9-15
 */
class WechatMchPayCenter {
    const API_MCHPAY_URL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';   //接口链接
    
    private $appid;
    private $key;
    private $mchid;
    private $comId = 0;
    public $message='';

    /**
     * 
     * @param type $comId
     * @param type $appid
     * @param type $mchid
     */
    public function __construct($comId, $appid, $key, $mchid) {
         
        $this->appid = $appid;
        $this->key=$key;
        $this->mchid = $mchid; 
        $this->comId = $comId;
        
    }
    
    /**
     * 生成付款
     * @param type $amount
     * @param type $openid
     * @param type $desc
     * @return type
     */
    public function createPayment($amount, $orderNo, $openid, $desc) {
        
        $model = new WechatMchpayModel();
        $model->com_id=$this->comId;
        $model->mp_appid = $this->appid;
        $model->mchid = $this->mchid;
        $model->nonce_str=md5(uniqid(true));
        $model->partner_trade_no = $orderNo;
        $model->amount = $amount * 100;
        $model->check_name="NO_CHECK";     //NO_CHECK：不校验真实姓名FORCE_CHECK：强校验真实姓名（未实名认证的用户会校验失败，无法转账） OPTION_CHECK：针对已实名认证的用户才校验真实姓名（未实名认证用户不校验，可以转账成功）
        $model->openid = $openid;
        $model->re_user_name='';
        $model->desc = $desc;
        $model->spbill_create_ip=Net::getIp();
        $model->create_time = date('Y-m-d H:i:s');
        
        $params=array(
            'mch_appid'=>$model->mp_appid,
            'mchid'=>$model->mchid,
            'nonce_str'=>$model->nonce_str,
            'partner_trade_no'=>$model->partner_trade_no,
            'openid'=>$model->openid,
            'check_name'=>$model->check_name,
            're_user_name'=>$model->re_user_name,
            'amount'=>$model->amount,
            'desc'=>$model->desc,
            'spbill_create_ip'=>$model->spbill_create_ip,
        );
        $model->sign=$this->makeSign($params);
        $params['sign']=$model->sign;
        
        if(!$model->save()) {
            throw new RuntimeException($model->getFirstErrorDesc());
        }
        return $this->gotoApi($model,$params);
    }
    
    /*
     * 生成付款签名
     */
    private function makeSign($params){ //生成签名
        ksort($params);  //排序	
        $sign = '';
        foreach ($params as $k=>$v){ 
                if(trim($v)==''){				 //对值为空的键去除掉
                        unset($params[$k]);
                }
                else
                {
                    $sign .=$k.'='.$v.'&' ;
                }
        }

        $stringSign = $sign."key=".$this->key;
        $sign = strtoupper(md5($stringSign));

        return  $sign ; 
    }
    
    /*
     * 调用微信企业付款api
     */
    private function gotoApi(WechatMchpayModel $model,$params)
    {
        $pem=$this->getPem();
        
        $xml = XML::arrayToXml($params);
        
        $http = HTTPClient::getInstance();
        $res = XML::xmlToArray($http->post_ssl(self::API_MCHPAY_URL, $xml, $pem, $this->mchid));
        
        $model->return_code=isset($res['return_code'])?$res['return_code']:'';
        $model->return_msg=isset($res['return_msg'])?$res['return_msg']:'';
        
        if(!$model->save()) {
            throw new RuntimeException($model->getFirstErrorDesc());
        }
        if($res['return_code']=="SUCCESS")
        {
            $this->message='微信企业付款成功！';
            return true;
        }
        else
        {
            $this->message=$res['return_msg'];
            return false;
        }
    	return $res;
    }
    
    /*
     * 获取密钥证书文件
     */
    private function getPem()
    {
        $mpaModel = MicroPayAccount::getWechatModelByWid($this->comId);
        
        if(!$mpaModel)
        {
            $this->message='你的微信支付账号不存在!系统自动发放红包返佣失败。<br>请进入公众号管理，'
                    . '点击左侧支付方式管理，添加微信支付配置，并上传证书和密钥文件。ps：证书和密钥文件在微信支付商户平台下载。'; 
            return  false ; 
        }
        if(!isset($mpaModel->cert) || !isset($mpaModel->cert_key) || !isset($mpaModel->rootca) )
        {
            $this->message='微信支付账没有上传证书，系统自动发放红包返佣失败。<br>请进入公众号管理，'
                    . '点击左侧支付方式管理，上传证书和密钥文件。ps：证书和密钥文件在微信支付商户平台下载。'; 
            return  false ; 
        }
        $api_params = json_decode($mpaModel->api_params,true);
        $api_params['cert']=$mpaModel->cert;
        $api_params['cert_key']=$mpaModel->cert_key;
        $api_params['rootca']=$mpaModel->rootca;
        
        $pem = array(); 
        $pem['cert'] = Yii::app()->params['uploadPathWx'].$api_params['cert'];
        $pem['cert_key'] = Yii::app()->params['uploadPathWx'].$api_params['cert_key'];	
        $pem['rootca'] =Yii::app()->params['uploadPathWx'].$api_params['rootca'];
        
        return $pem;
    }
}
